﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace AutoDeployForSims.Model
{
    public class WindowActivator
    {
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool SwitchToThisWindow(IntPtr hWnd, bool turnOn);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetForegroundWindow();

        public static void ActivateProcessWindow(int processId)
        {
            try
            {
                // 获取进程
                Process process = Process.GetProcessById(processId);

                // 确保进程有主窗口句柄
                //if (process.MainWindowHandle == IntPtr.Zero)
                //{
                //    Console.WriteLine($"进程 {process.Id} 没有主窗口或窗口尚未创建。");
                //    return;
                //}

                //// 检查是否已经是前台窗口，避免循环激活
                //IntPtr currentForeground = GetForegroundWindow();
                //if (currentForeground == process.MainWindowHandle)
                //{
                //    Console.WriteLine($"进程 {process.Id} 的窗口已经是前台窗口。");
                //    return;
                //}

                // 尝试激活窗口
                if (!SetForegroundWindow(process.MainWindowHandle))
                {
                    // 如果SetForegroundWindow失败，可能是由于UIPI（用户界面特权隔离）限制，尝试SwitchToThisWindow作为备选
                    SwitchToThisWindow(process.MainWindowHandle, true);
                }

                Console.WriteLine($"进程 {process.Id} 的窗口已被激活。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"激活进程窗口失败: {ex.Message}");
            }
        }
    }
}
